package com.tcxhb.job.core.schedule.handler;

import com.tcxhb.job.core.constants.JobHandlerMapping;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/5
 */
@Service
public class HandlerFactory implements ApplicationContextAware, SmartInitializingSingleton {
    private ApplicationContext context;
    public final static Map<String, JobHandler> handlerMap = new ConcurrentHashMap<String, JobHandler>();

    public JobHandler getBean(String type) {
        return handlerMap.get(type);
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, Object> beans = this.context.getBeansWithAnnotation(JobHandlerMapping.class);
        if (beans == null) {
            return;
        }
        for (Object bean : beans.values()) {
            JobHandlerMapping command = bean.getClass().getAnnotation(JobHandlerMapping.class);
            handlerMap.put(command.name(), (JobHandler) bean);
        }
        return;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
